package edu.towson.cis.cosc490.jpanne.npr.main;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import edu.towson.cis.cosc490.jpanne.npr.R;
import edu.towson.cis.cosc490.jpanne.npr.data.Constants;
import edu.towson.cis.cosc490.jpanne.npr.data.NPRData;
import edu.towson.cis.cosc490.jpanne.npr.parsers.AndroidSaxFeedParser;

public class SplashActivity extends Activity {
	private List<NPRItem> nprList;
	private NPRData nprData;
	private String feedURL = "http://www.npr.org/rss/rss.php?id=1001";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		nprData = new NPRData(this);
		setContentView(R.layout.activity_splash);
		IntentLauncher launcher = new IntentLauncher();
		launcher.start();
	}
	
	private List<String> getFeedList(){
    	try{
	    	AndroidSaxFeedParser parser = new AndroidSaxFeedParser(feedURL);
	       	nprList = parser.parse();
	    	List<String> titles = new ArrayList<String>(nprList.size());
	    	for (NPRItem rd : nprList){
	    		titles.add(rd.getTitle());
	    		try{
	    			addNPRItem(rd.getDescription(), "" + rd.getTitle(), rd.getLink().toString(), rd.getDate()); 
	   			 }catch(Exception e){e.printStackTrace();}	
	    	}
	    	return titles;
    	} catch (Throwable t){ return null;}
    }
	
	private void addNPRItem(String des,String title,String link,String pubDate){
        SQLiteDatabase db = nprData.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(Constants.DES, des);
        values.put(Constants.TITLE, title);
        values.put(Constants.LINK, link);
        values.put(Constants.PUBDATE, pubDate);
        db.insertOrThrow(Constants.TABLE_NAME, null, values);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.splash, menu);
		return true;
	}
	
	 private class IntentLauncher extends Thread {
		  public void run() {
			 List<String> list = getFeedList();
		     try {
		        Thread.sleep(3000);
		     } catch (Exception e) {
		        Log.e("ERROR", e.getMessage());
		     }
		     Intent intent = new Intent(SplashActivity.this, NPRMainActivity.class);
		     intent.putStringArrayListExtra("FeedList", (ArrayList<String>)list);
		     SplashActivity.this.startActivity(intent);
		     SplashActivity.this.finish();
		  }
	 }

}
